# This file is used to create a login blueprint for the flask application.
# The blueprint is used to handle the login functionality of the application.

import datetime
from flask import Blueprint
from flask import request
from flask import jsonify
from settings import *
from database import SqliteSingleton
from database.user_info_table_methods import UserInfoTableMethods
from database.notification_types_table_methods import NotificationTypesTableMethods
from database.sms_methods import SmsMethods
from database.sms_time_slots_methods import SmsTimeSlotsMethods

import logging

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

web_blueprint = Blueprint('web_blueprint', __name__)


@web_blueprint.route('/add_notification_types', methods=['POST'])
def add_notification_types():
    
    template_code = request.form.get('template_code')
    type_name = request.form.get('type_name')



    if not template_code or not type_name:
        return jsonify({
            "status": -1,
            "errorCode": 1000,
            "erorrMsg": "template_code or type_name is missing",
            "resultBody": None
        })

    # Check if the user exists in the database
    with SqliteSingleton() as conn:
        cursor = conn.cursor()
        notification_types_table_methods = NotificationTypesTableMethods(conn, cursor)

        result = notification_types_table_methods.insert_notification_type(template_code, type_name)

        return jsonify({
            "status": 1,
            "errorCode": None,
            "erorrMsg": None,
            "resultBody": "Notification type added successfully"
        })
    
@web_blueprint.route('/update_notification_type_current_status_by_id', methods=['POST'])
def update_notification_type_current_status_by_id():

    notification_type_id = request.form.get('notification_type_id')
    current_status = request.form.get('current_status', "blocked")

    if not notification_type_id or not current_status:
        return jsonify({
            "status": -1,
            "errorCode": 1000,
            "erorrMsg": "notification_type_id or current_status is missing",
            "resultBody": None
        })
    

    
    # Check if the user exists in the database
    with SqliteSingleton() as conn:
        cursor = conn.cursor()
        notification_types_table_methods = NotificationTypesTableMethods(conn, cursor)

        result = notification_types_table_methods.update_notification_type_current_status_by_id(notification_type_id, current_status)

        return jsonify({
            "status": 1,
            "errorCode": None,
            "erorrMsg": None,
            "resultBody": "Notification type current status updated successfully"
        })
    
@web_blueprint.route('/get_notification_types_by_all')
def get_notification_types():
    
    # Check if the user exists in the database
    with SqliteSingleton() as conn:
        cursor = conn.cursor()
        # user_info_table_methods = UserInfoTableMethods(cursor)
        notification_types_table_methods = NotificationTypesTableMethods(conn, cursor)

        result = notification_types_table_methods.get_notification_types()

        return jsonify({
            "status": 1,
            "errorCode": None,
            "erorrMsg": None,
            "resultBody": result
        })
    
@web_blueprint.route('/update_notification_type_by_id', methods=['POST'])
def update_notification_type_by_id():

    notification_type_id = request.form.get('notification_type_id')
    template_code = request.form.get('template_code')
    type_name = request.form.get('type_name')


    if not notification_type_id or not template_code or not type_name:
        return jsonify({
            "status": -1,
            "errorCode": 1000,
            "erorrMsg": "notification_type_id, template_code or type_name is missing",
            "resultBody": None
        })

    # Check if the user exists in the database
    with SqliteSingleton() as conn:
        cursor = conn.cursor()
        notification_types_table_methods = NotificationTypesTableMethods(conn, cursor)

        result = notification_types_table_methods.update_notification_type_by_id(notification_type_id, template_code, type_name)

        return jsonify({
            "status": 1,
            "errorCode": None,
            "erorrMsg": None,
            "resultBody": "Notification type updated successfully"
        })

@web_blueprint.route('/select_sms_records')
def select_sms_records():
    # def select_sms_records(self, device_sn=None, phone=None, template_code=None, send_status=None, start_time=None, end_time=None, limit=20, page=1):

    device_sn = request.args.get('device_sn', None)
    phone = request.args.get('phone', None)
    template_code = request.args.get('template_code', None)
    send_status = request.args.get('send_status', None)
    start_time = request.args.get('start_time', None)
    end_time = request.args.get('end_time', None)
    limit = request.args.get('limit', 20)
    page = request.args.get('page', 1)

    # YYYY-MM-DD HH:MM:SS 时间格式判断
    if start_time:
        if not (len(start_time.split('-')) == 3 and len(start_time.split(':')) == 3):
            return jsonify({
                "status": -1,
                "errorCode": 1000,
                "erorrMsg": "start_time or end_time format error: YYYY-MM-DD HH:MM:SS",
                "resultBody": None
            })
        # 北京时间转UTC时间
        beijing_time = datetime.datetime.strptime(start_time, '%Y-%m-%d %H:%M:%S')
        utc_time = beijing_time - datetime.timedelta(hours=8)
        start_time = utc_time.strftime('%Y-%m-%d %H:%M:%S')
        
    if end_time:
        if not (len(end_time.split('-')) == 3 and len(end_time.split(':')) == 3):
            return jsonify({
                "status": -1,
                "errorCode": 1000,
                "erorrMsg": "start_time or end_time format error: YYYY-MM-DD HH:MM:SS",
                "resultBody": None
            })
    
        beijing_time = datetime.datetime.strptime(end_time, '%Y-%m-%d %H:%M:%S')
        utc_time = beijing_time - datetime.timedelta(hours=8)
        end_time = utc_time.strftime('%Y-%m-%d %H:%M:%S')
    
    if send_status and send_status not in ["OK"]:

        send_status = "NO"
        

    with SqliteSingleton() as conn:

        cursor = conn.cursor()

        notification_types_table_methods = SmsMethods(conn, cursor)

        result = notification_types_table_methods.select_sms_records(device_sn, phone, template_code, send_status, start_time, end_time, limit, page)

        count_sms_records = notification_types_table_methods.count_sms_records(device_sn, phone, template_code, send_status, start_time, end_time)
        if result is None or count_sms_records is None:
            return jsonify({
                "status": -1,
                "errorCode": 1001,
                "erorrMsg": "error in select_sms_records",
                "resultBody": None
            })

        # 电话号码隐藏中间四位
        for item in result:
            item['phone'] = item['phone'][:3] + '****' + item['phone'][-4:]

        return jsonify({
            "status": 1,
            "errorCode": None,
            "erorrMsg": None,
            "resultBody": {
                "list": result,
                "total": count_sms_records
            }
        })
    

@web_blueprint.route('/insert_sms_time_slots', methods=['POST'])
def insert_sms_time_slots():
    # def insert_sms_time_slots(self, start_time, end_time):

    start_time = request.form.get('start_time')
    end_time = request.form.get('end_time')

    if not start_time or not end_time:
        return jsonify({
            "status": -1,
            "errorCode": 1000,
            "erorrMsg": "start_time or end_time is missing",
            "resultBody": None
        })

    # HH:MM:SS 时间格式判断
    if not (len(start_time.split(':')) == 3 and len(end_time.split(':')) == 3):
        return jsonify({
            "status": -1,
            "errorCode": 1001,
            "erorrMsg": "start_time or end_time format error: HH:MM:SS",
            "resultBody": None
        })

    

    with SqliteSingleton() as conn:

        cursor = conn.cursor()

        sms_time_slots_methods = SmsTimeSlotsMethods(conn, cursor)

        result = sms_time_slots_methods.insert_sms_time_slots(start_time, end_time)

        return jsonify({
            "status": 1,
            "errorCode": None,
            "erorrMsg": None,
            "resultBody": "Sms time slots added successfully"
        })
    
# def block_sms_time_slots(self): # Block all SMS time slots
@web_blueprint.route('/block_sms_time_slots', methods=['POST'])
def block_sms_time_slots():
    with SqliteSingleton() as conn:

        cursor = conn.cursor()

        sms_time_slots_methods = SmsTimeSlotsMethods(conn, cursor)

        result = sms_time_slots_methods.block_sms_time_slots()

        return jsonify({
            "status": 1,
            "errorCode": None,
            "erorrMsg": None,
            "resultBody": "All Sms time slots blocked successfully"
        })
    
# select_sms_time_slots_by_status_active
@web_blueprint.route('/select_sms_time_slots_by_status_active')
def select_sms_time_slots_by_status_active():
    with SqliteSingleton() as conn:

        cursor = conn.cursor()

        sms_time_slots_methods = SmsTimeSlotsMethods(conn, cursor)

        result = sms_time_slots_methods.select_sms_time_slots_by_status_active()

        return jsonify({
            "status": 1,
            "errorCode": None,
            "erorrMsg": None,
            "resultBody": result
        })
    
#select_all_sms_time_slots
@web_blueprint.route('/select_all_sms_time_slots')
def select_all_sms_time_slots():
    with SqliteSingleton() as conn:

        cursor = conn.cursor()

        sms_time_slots_methods = SmsTimeSlotsMethods(conn, cursor)

        result = sms_time_slots_methods.select_all_sms_time_slots()

        return jsonify({
            "status": 1,
            "errorCode": None,
            "erorrMsg": None,
            "resultBody": result
        })
    
# def delete_sms_time_slots_by_id(self, id): # Delete SMS time slot by id
@web_blueprint.route('/delete_sms_time_slots_by_id', methods=['POST'])
def delete_sms_time_slots_by_id():
    sms_time_slots_id = request.form.get('id')

    if not sms_time_slots_id:
        return jsonify({
            "status": -1,
            "errorCode": 1000,
            "erorrMsg": "sms_time_slots_id is missing",
            "resultBody": None
        })

    with SqliteSingleton() as conn:

        cursor = conn.cursor()

        sms_time_slots_methods = SmsTimeSlotsMethods(conn, cursor)

        result = sms_time_slots_methods.delete_sms_time_slots_by_id(sms_time_slots_id)

        return jsonify({
            "status": 1,
            "errorCode": None,
            "erorrMsg": None,
            "resultBody": "Sms time slot deleted successfully"
        })
    
# update_sms_time_slots_status_by_id(self, id, status): # Update SMS time slot by id
@web_blueprint.route('/update_sms_time_slots_status_by_id', methods=['POST'])
def update_sms_time_slots_status_by_id():
    sms_time_slots_id = request.form.get('sms_time_slots_id')
    status = request.form.get('status')

    if not sms_time_slots_id or not status:
        return jsonify({
            "status": -1,
            "errorCode": 1000,
            "erorrMsg": "sms_time_slots_id or status is missing",
            "resultBody": None
        })
    
    if status not in ["active", "blocked"]:
        return jsonify({
            "status": -1,
            "errorCode": 1001,
            "erorrMsg": "status error: active or blocked",
            "resultBody": None
        })

    with SqliteSingleton() as conn:

        cursor = conn.cursor()

        sms_time_slots_methods = SmsTimeSlotsMethods(conn, cursor)

        result = sms_time_slots_methods.update_sms_time_slots_status_by_id(sms_time_slots_id, status)

        return jsonify({
            "status": 1,
            "errorCode": None,
            "erorrMsg": None,
            "resultBody": "Sms time slot status updated successfully"
        })
    
#  def update_sms_time_slots_time_by_id(self, id, start_time, end_time): # Update SMS time slot by id
@web_blueprint.route('/update_sms_time_slots_time_by_id', methods=['POST'])
def update_sms_time_slots_time_by_id():
    sms_time_slots_id = request.form.get('sms_time_slots_id')
    start_time = request.form.get('start_time')
    end_time = request.form.get('end_time')

    if not sms_time_slots_id or not start_time or not end_time:
        return jsonify({
            "status": -1,
            "errorCode": 1000,
            "erorrMsg": "sms_time_slots_id, start_time or end_time is missing",
            "resultBody": None
        })

    # HH:MM:SS 时间格式判断
    if not (len(start_time.split(':')) == 3 and len(end_time.split(':')) == 3):
        return jsonify({
            "status": -1,
            "errorCode": 1001,
            "erorrMsg": "start_time or end_time format error: HH:MM:SS",
            "resultBody": None
        })
                      

    with SqliteSingleton() as conn:

        cursor = conn.cursor()

        sms_time_slots_methods = SmsTimeSlotsMethods(conn, cursor)

        result = sms_time_slots_methods.update_sms_time_slots_time_by_id(sms_time_slots_id, start_time, end_time)

        return jsonify({
            "status": 1,
            "errorCode": None,
            "erorrMsg": None,
            "resultBody": "Sms time slot time updated successfully"
        })




